package 二叉树;

import com.sun.source.tree.Tree;

public class 平衡二叉树 {
    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public boolean isBalanced(TreeNode root){
         return getHeight(root)!=-1;
    }
    public int getHeight(TreeNode root){
         if (root==null) return 0;
        int leftheight = getHeight(root.left);
        if (leftheight==-1)
            return -1;
        int rightheight = getHeight(root.right);
        if (rightheight==-1)
            return -1;
        if (Math.abs(leftheight-rightheight)>1){
            return -1;
        }
        return Math.max(leftheight,rightheight)+1;

    }
}
